/* eslint-disable */
//
import { Controller, Get, Query } from '@nestjs/common';
import { FileUploadService } from './file-upload.service';
import { config } from '@/utils/config/alioss';
import * as crypto from 'crypto';
import { Req } from '@nestjs/common/decorators';
import { AllowNoToken } from '@/decorators/token.decorator';
import { responseMessage } from '@/utils';
import { Crud, CrudAuth, CrudController } from '@dataui/crud';
import { FileUpload } from '@/module/file-upload/entities/file-upload.entity';
import { User } from '@/user/user.service';

@Crud({
  model: {
    type: FileUpload,
  },
})
@CrudAuth({
  property: 'user',
  filter: (user: User) => ({
    id: user.id,
  }),
})
@Controller('file-upload')
export class FileUploadController implements CrudController<FileUpload> {
  constructor(public service: FileUploadService) {}

  @Get('ossSign')
  @AllowNoToken()
  ossSign(@Query('ext') ext: string): any {
    const {
      bucket,
      region,
      expAfter,
      maxSize,
      dirPath,
      accessKeyId,
      accessKeySecret,
      callbackIp,
      callbackPort,
      callbackPath,
    } = config;
    const host = `https://${bucket}.${region}.aliyuncs.com`; //你的oss完整地址
    const expireTime = new Date().getTime() + expAfter;
    const expiration = new Date(expireTime).toISOString();
    const policyString = JSON.stringify({
      expiration,
      conditions: [
        ['content-length-range', 0, maxSize],
        ['starts-with', '$key', dirPath],
      ],
    });
    // @ts-ignore
    const bufferStr = Buffer(policyString);
    console.log('bufferStr:', bufferStr);
    const policy = bufferStr.toString('base64');
    console.log('policy: ', policy);
    const if_online_no = callbackIp.startsWith('admin');
    const Signature = crypto
      .createHmac('sha1', accessKeySecret)
      .update(policy)
      .digest('base64');
    const callbackBody = {
      callbackUrl:
        `http` +
        `://${callbackIp}` +
        (if_online_no ? '' : `:${callbackPort}`) +
        `/${callbackPath}`,
      callbackHost: `${callbackIp}`,
      callbackBody: '{"filename": ${object},"size": ${size}}',
      callbackBodyType: 'application/json',
    };
    console.log(callbackBody);
    // @ts-ignore
    const callback = Buffer(JSON.stringify(callbackBody)).toString('base64');

    const result = {
      Signature,
      policy,
      host,
      OSSAccessKeyId: accessKeyId,
      key: dirPath + expireTime + ext,
      success_action_status: 200,
      dirPath,
      callback,
    };
    return responseMessage(result, 'oss签名成功', 200);
  }

  @Get('ossCallback')
  @AllowNoToken()
  ossCallback(@Req() req) {
    console.log('这有什么用吗?');
    return {
      ...req.body,
    };
  }
}
